import axios from 'axios'
import qs from 'qs'
import {
  handleRequestHeader as handleChangeRequestHeader,
  handleAuth as handleConfigureAuth,
  handleAuthError,
  handleGeneralError,
  handleNetworkError
} from './tools'

type Fn = (data: FcResponse<any>) => unknown
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE3MzY2ODc2MTUsImlhdCI6MTczNjYwMTIxNX0.csdTEuMnbJ45eXssayzwp22V0XU83yFAjvcHm1AESS4
interface IAnyObj {
  [index: string]: unknown
}

interface FcResponse<T> {
  resCode: string
  message: string
  data: T
}
const instance = axios.create({
  baseURL: 'http://123.157.211.154:10001/',
  timeout: 5000
})

// 请求拦截
instance.interceptors.request.use((config) => {
  config = handleChangeRequestHeader(config)
  config = handleConfigureAuth(config)
  console.log('request', config)
  return config
})

// 响应拦截
instance.interceptors.response.use(
  (response) => {
    console.log('response', response)
    if (response.status !== 200)
      return Promise.reject({
        status: response.status,
        message: response.data.detail
      })
    const { resCode, message: resMessage } = response.data
    handleAuthError(resCode)
    handleGeneralError(resCode, resMessage)
    return response
  },
  (err) => {
    return Promise.reject({
      status: err.response.status,
      message: err.response.data.detail
    })
  }
)
export default abstract class api {
  static async get<T>(
    url: string,
    params: IAnyObj = {},
    clearFn?: Fn
  ): Promise<[any, FcResponse<T> | undefined]> {
    return new Promise((resolve) => {
      instance
        .get(url, { params })
        .then((result) => {
          let res: FcResponse<T>
          if (clearFn !== undefined) {
            res = clearFn(result.data) as unknown as FcResponse<T>
          } else {
            res = result.data as FcResponse<T>
          }
          resolve([null, res as FcResponse<T>])
        })
        .catch((err) => {
          resolve([err, undefined])
        })
    })
  }
  static async post<T>(
    url: string,
    data: IAnyObj,
    params: IAnyObj = {}
  ): Promise<[any, FcResponse<T> | undefined]> {
    return new Promise((resolve) => {
      const paramStr = qs.stringify(data)
      instance
        .post(url, paramStr, {
          headers: {
            accept: 'application/json',
            'Content-Type': 'application/json'
          },
          ...params
        })
        .then((result) => {
          resolve([null, result.data as FcResponse<T>])
        })
        .catch((err) => {
          console.log(err, 'err')
          handleNetworkError(err)
          resolve([err, undefined])
        })
    })
  }
}
